package ro.ubbcluj.cs.damate.managers.resources;

import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author Lóránd Fazakas (lfazakas)
 *         Date: 2013.06.30.
 *         Time: 17:29
 */
public class ResourceTree {

    private final Set<ResourceTree> children = new LinkedHashSet<ResourceTree>();
    private final TreeNode data;

    ResourceTree(TreeNode data) {
        this.data = data;
    }

    ResourceTree child(String data, String fullPath, Integer type, boolean first, boolean last) {
        for (ResourceTree child: children ) {
            if (child.data.getData().equals(data)) {
                return child;
            }
        }
        TreeNode newNode = null;
        if (last && type == 1) {
            newNode = createFileTreeNode(data);
        } else if (first && "src".equalsIgnoreCase(data)) {
            newNode = new DefaultTreeNode("src-folder", data, this.data);
        } else if (!first && fullPath.startsWith("src")) {
            newNode = new DefaultTreeNode("package", data, this.data);
        } else if (last && type == 2) {
            newNode = new DefaultTreeNode("folder", data, this.data);
        }
        return child(new ResourceTree(newNode));
    }

    private TreeNode createFileTreeNode(String fileName) {
        if (fileName.equalsIgnoreCase("build.properties")) {
            return new DefaultTreeNode("build-file", fileName, this.data);
        } else if (fileName.equalsIgnoreCase("plugin.xml")) {
            return new DefaultTreeNode("plugin-xml", fileName, this.data);
        } else if (fileName.equalsIgnoreCase("contexts.xml")) {
            return new DefaultTreeNode("contexts-xml", fileName, this.data);
        } else if (fileName.equalsIgnoreCase("MANIFEST.MF")) {
            return new DefaultTreeNode("manifest-file", fileName, this.data);
        } else if (fileName.matches(".+\\.java")) {
            return new DefaultTreeNode("java-file", fileName, this.data);
        } else if (fileName.matches(".+\\.properties")) {
            return new DefaultTreeNode("properties-file", fileName, this.data);
        }  else if (fileName.matches(".+\\.xml")) {
            return new DefaultTreeNode("xml-file", fileName, this.data);
        }
        return new DefaultTreeNode("file", fileName, this.data);
    }

    ResourceTree child(ResourceTree child) {
        children.add(child);
        return child;
    }
}
